/*
 *  Copyright (C) 2010 Matthias Buch-Kromann <mbk.isv@cbs.dk>
 * 
 *  This file is part of the MatrixParser package.
 *  
 *  The MatrixParser program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 * 
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.osdtsystem.matrixparser.main;

import java.io.File;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.osdtsystem.matrixparser.logging.Log;

/**
 * Contains all default options used by the IRP parser
 * @author Matthias Buch-Kromann <mbk.isv@cbs.dk>
 */
public class Options {
    static Map<String,String> options = defaultOptions();
    static Map<String,Level> levels = levels();

    static Map<String,Level> levels() {
        Map<String,Level> newLevels = new HashMap<String,Level>();
        newLevels.put("ALL", Level.ALL);
        newLevels.put("CONFIG", Level.CONFIG);
        newLevels.put("FINE", Level.FINE);
        newLevels.put("FINER", Level.FINER);
        newLevels.put("FINEST", Level.FINEST);
        newLevels.put("INFO", Level.INFO);
        newLevels.put("OFF", Level.OFF);
        newLevels.put("SEVERE", Level.SEVERE);
        newLevels.put("WARNING", Level.WARNING);
        return(newLevels);
    }

    static Map<String,String> defaultOptions() {
        Map<String,String> defaults = new HashMap<String,String>();

        // Treebank files (training and evaluation)
        defaults.put("fileformat", "conll"); // or: "tag"
        defaults.put("train.file", "");
        defaults.put("train.file.dev", "");
        defaults.put("complements.file", "");
        defaults.put("eval.file", "");

        // Parsers, model files, and output files
        defaults.put("eval.ofile", "");
        defaults.put("eval.traincorpus", "false");
        defaults.put("eval.devcorpus", "false");

        // Training parameters
        defaults.put("train.parser", ""); // "mst" or "irp"
        defaults.put("model.ifile", "");
        defaults.put("model.ofile", "");
        defaults.put("model.fixweights", "true");
        defaults.put("train.iterations", "20");
        defaults.put("scorer.type", "linear");
        defaults.put("learner.type", "mira"); // or: "perceptron"
        defaults.put("loss.type", "labelled");
        defaults.put("loss.wrongHead", "1");
        defaults.put("loss.wrongLabel", "1");

        // Feature selection parameters
        defaults.put("extractors", "mst:mstlab");
        defaults.put("genes", ""); // hex number, 1's indicate that the gene is turned off

        // Default parameters for incremental repair parser
        defaults.put("irp.ktypes", "10");
        defaults.put("irp.kedges", "50");
        defaults.put("irp.kheads", "1");

        // Logging parameters
        defaults.put("log.level", "CONFIG");

        // Return defaults
        return defaults;
    }

    public static void parseArgs(String[] args) {
        int pos = 0;
        int nonopts = 0;
        while (pos < args.length) {
            if (args[pos].substring(0, 1).equals("-")) {
                // Find first "=" in string
                int eqpos = args[pos].indexOf("=");
                String key, value = null;
                if (eqpos > 0) {
                    key = args[pos].substring(1, eqpos);
                    if (options.containsKey(key)) {
                        value = args[pos].substring(eqpos + 1);
                        options.put(key, value);
                    }
                }
                if (value == null)
                    Log.severe("Unknown option: " + args[pos]);
            } else if (nonopts == 0) {
                options.put("train.file", args[pos]);
                ++nonopts;
            } else if (nonopts == 1) {
                options.put("eval.file", args[pos]);
                ++nonopts;
            } else {
                Log.severe("Invalid command-line argument: " + args[pos]);
            }
            ++pos;
        }

        // Log options
        StringBuilder s = new StringBuilder("Options\n");
        List<String> keys = new ArrayList<String>(options.keySet());
        Collections.sort(keys);
        for (String key : keys) {
            s.append(key);
            s.append("=");
            s.append(options.get(key));
            s.append("\n");
        }
        Log.config(s);
        bitsetOption("genes");

    }

    public static String option(String key) {
        return options.get(key);
    }

    public static File fileOption(String key) {
        String filename = option(key);
        return filename == null ? null : new File(filename);
    }

    public static int intOption(String key) {
        return Integer.parseInt(options.get(key));
    }

    public static boolean booleanOption(String key) {
        return Boolean.parseBoolean(options.get(key));
    }

    public static double doubleOption(String key) {
        return Double.parseDouble(options.get(key));
    }

    public static Level levelOption(String key) {
        Level result = levels.get(key);
        return result == null ? Level.CONFIG : result;
    }

    public static BitSet bitsetOption(String key) {
        // Check for majority bitset option
        String bitString = options.get(key);
        if (bitString.startsWith("majority:")) {
            bitString = bitString.substring("majority:".length());
            String[] bitStrings = bitString.split("+");
            BitSet[] bitSets = new BitSet[bitStrings.length];
            for (int i = 0; i < bitStrings.length; ++i)
                bitSets[i] = bitset(bitStrings[i]);
            return majorityBitSet(bitSets);
        }
        return bitset(bitString);
    }
    
    public static BitSet bitset(String bitString) {
        // Calculate bitset directly
        BitSet bitset = new BitSet();
        int bitIndex = 0;
        int basebits = 4;
        int radix = 1 << basebits;
        for (int i = bitString.length() - 1; i >= 0; --i) {
            String digit = bitString.substring(i, i + 1);
            int number = Integer.parseInt(digit, radix);
            for (int b = 0; b < basebits; ++b) {
                bitset.set(bitIndex, (number & 1) == 1);
                number = number >> 1;
                bitIndex++;
            }
        }
        return bitset;
    }

    public static BitSet majorityBitSet(BitSet... bitsets) {
        BitSet result = new BitSet();
        for (int bit = 0; bit < bitsets[0].size(); ++bit)  {
            // Count bitsets that set this bit
            int count = 0;
            for (int s = 0; s < bitsets.length; ++s)
                if (bitsets[s].get(bit))
                    ++count;

            // Set bit if set by majority
            if (count * 2 > bitsets.length)
                result.set(bit);
        }
        return result;
    }

    public static String bitString(BitSet bitset) {
        StringBuilder sb = new StringBuilder();
        int highestBit = bitset.size();
        int bit0 = highestBit - (highestBit % 4);
        boolean significant = false;
        while (bit0 >= 0) {
            int digit = 0;
            if (bitset.get(bit0))
                digit += 1;
            if (bitset.get(bit0 + 1))
                digit += 2;
            if (bitset.get(bit0 + 2))
                digit += 4;
            if (bitset.get(bit0 + 3))
                digit += 8;
            if (significant || digit != 0 || bit0 == 0) {
                sb.append((char) (digit + (digit < 10 ? 48 : 87)));
                significant = true;
            }
            bit0 -= 4;
        }
        return sb.toString();
    }
}
